package org.sensation.server.operation.command.setup;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.sensation.context.Context;
import org.sensation.server.file.SensationFileReceiveServer;
import org.sensation.server.operation.command.CommandController;
import org.sensation.server.operation.management.ManagementOffice;
import org.sensation.server.operation.request.Command;
import org.sensation.server.operation.request.OperationRequest;
import org.sensation.server.operation.response.Response;

public class SetupCommandController implements CommandController{
	private Logger logger = Logger.getLogger(SetupCommandController.class);
	private String folderPath = Context.get("folderPath");
	
	public void service(OperationRequest request, Response response) throws Exception {
		logger.debug("SetupCommandController start");
		
		SensationFileReceiveServer server = setupFileTrasferServer(request);
		logger.debug("SensationFileTransferServer setup " + server);
		
		startFileTrasferServer(request, server);
		logger.debug("SensationFileTransferServer start " + server);
		
		Integer seqID = ManagementOffice.registNewOperationRequest(request);
		logger.debug("SensationFileTransferServer regist to ManagementOffice [seqID : " + seqID+"]");
		
		Command command = createResultCommand(seqID);
		response.complete(command);
		logger.debug("SetupCommandController end");
	}

	private Command createResultCommand(Integer seqID) {
		Command command = new Command();
		command.setSeqID(seqID);
		command.setCommand("complete");
		return command;
	}

	private void startFileTrasferServer(OperationRequest request,
			SensationFileReceiveServer server) {
		Thread thread = new Thread(server);
		thread.start();
		request.setFileReceiveServer(server);
	}

	private SensationFileReceiveServer setupFileTrasferServer(
			OperationRequest request) throws IOException {
		String filePath = folderPath + request.getFileName();
		return new SensationFileReceiveServer(filePath, request.getFileSize());
	}

	
	public SetupCommandController() {
		super();
	}
	public SetupCommandController(String folderPath) {
		super();
		this.folderPath = folderPath;
	}
}
